package cn.powerchaintech.common.cimeparser;

import java.util.ArrayList;
import java.util.List;

public class CimELine {
    private StringBuilder buffer;
    private List<String> data = new ArrayList<>();

    public static final String HEADER_PREFIX = "@";
    public static final String DESCRIBE_PREFIX = "//";
    public static final String DATA_PREFIX = "#";

    private Type type;

    public enum Type {
        HEADER, DATA, DESCRIBE
    }

    public CimELine(String line) {
        buffer = new StringBuilder();
        buffer.append(line);
        split(0, line.length());
        if(data.get(0).startsWith(HEADER_PREFIX)) {
            type = Type.HEADER;
        } else if(data.get(0).startsWith(DESCRIBE_PREFIX)) {
            type = Type.DESCRIBE;
        } else if(data.get(0).startsWith(DATA_PREFIX)) {
            type = Type.DATA;
        } else {
            throw new RuntimeException("Unknow type");
        }
    }

    public Type getType() {
        return type;
    }

    private void split(int start, int end) {
        boolean unquote = true; // 引号完
        StringBuilder item = new StringBuilder();
        for (int i = start; i < end; i++) {
            char c = buffer.charAt(i);
            if (c == '\'' || c == '\"') {
                unquote = !unquote;
            } else if ((c == ' ' || c == '\t') && unquote) {
                if (item.length() > 0) {
                    data.add(item.toString());
                    item = new StringBuilder();
                }
                continue;
            }
            item.append(c);
        }
        data.add(item.toString());
    }

    public int size() {
        return data.size();
    }

    public String get(int index) {
        return data.get(index);
    }
}
